//
//  VKRecordController.m
//  V-Learn
//
//  Created by liubo on 2019/2/12.
//  Copyright © 2019 yxk. All rights reserved.
//

#import "VKRecordController.h"
#import "VKRecordNiuWaCell.h"
#import "VKRecordRemenCell.h"
//#import "VKRecordModel.h"
#import "XHWebImageAutoSize.h"
#import "UIImageView+WebCache.h"
#import <YYModel.h>
#import "THScrollChooseView.h"
#import "VKRecordDetailVC.h"
#import "WKDakaImageTextVC.h"
#import "WKHotmenModel.h"//和社圈里的模型统一使用一个
@interface VKRecordController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong)UITableView *tableView;
@property(nonatomic,strong)NSArray *dataArray;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, assign) NSInteger pageNums;
@property(nonatomic,strong)NSMutableArray *sourceArray;
@property(nonatomic,strong)NSMutableArray *selectArray;//帅选数据
@property(nonatomic,assign)NSInteger selectDate;
@property(nonatomic,copy)NSString *dateString;

@end

@implementation VKRecordController
- (NSMutableArray *)selectArray{
    if (!_selectArray) {
        _selectArray = [NSMutableArray array];
    }
    return _selectArray;
}
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, ScreenH) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    }
    return _tableView;
}
-(NSMutableArray *)sourceArray{
    if (_sourceArray == nil) {
        _sourceArray = [[NSMutableArray alloc]init];
    }
    return _sourceArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.tableView];
    self.title = @"我的记录";
    [self setupRightItem];
    [self setupLeftRefresh];
    // 防止tableView闪动
    self.tableView.estimatedRowHeight = 0;
    self.tableView.estimatedSectionHeaderHeight = 0;
    self.tableView.estimatedSectionFooterHeight = 0;
//    [self reqestShuaixuanData];
}
- (void)reqestShuaixuanData{
    
    NSMutableDictionary *data = [NSMutableDictionary dictionary];
    NSString *token = [UserModel getUserModel].token;
    
    [data setObject:token forKey:@"token"];
    [data setObject:@"2019-3" forKey:@"date"];//2019-3 //获取
    [data setObject:@"1" forKey:@"page"];
    [data setObject:@"10"forKey:@"num"];
    [WYHXNetWorkService netWorkSerViceRequestWithGetUrl:WKClockRecordByDate_WKURL withPostParams:data withBlock:^(NSDictionary *result, NSError *error) {
        NSString *code = result[@"code"];
//        NSLog(@"%@",result);
        if ([code integerValue]==200) {
//            NSLog(@"result = %@ error= %@",result,error);
            
        }
    }];
    
}
//刷新
- (void)setupLeftRefresh
{   //下拉
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(setupLoadData)];
    //上拉
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(setupLoadMoreData)];
    
    [self.tableView.mj_header beginRefreshing];
}
- (void)setupLoadData{
    _page = 1;
    _pageNums = 10;
    [self setupData];
}
/**
 加载更多数据
 */
- (void)setupLoadMoreData{
    
    ++(_page);
    _pageNums = 10;
    [self setupData];
}//决定footer的状态
- (void)checkFooterState{
    
    [self.tableView.mj_footer endRefreshingWithNoMoreData];
}
- (void)setupData{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = @"正在加载...";
    [hud show:YES];
    
    NSMutableDictionary *dic = @{@"token":[UserModel getUserModel].token,@"page":[NSString stringWithFormat:@"%ld",(long)_page],@"num":[NSString stringWithFormat:@"%ld",(long)_pageNums]}.mutableCopy;
    VKWeakSelf(self)

    if (self.selectDate == 1) {
        dic = @{@"token":[UserModel getUserModel].token,@"date":self.dateString,@"page":[NSString stringWithFormat:@"%ld",(long)_page],@"num":[NSString stringWithFormat:@"%ld",(long)_pageNums]}.mutableCopy;
    }
    [WYHXNetWorkService netWorkSerViceRequestWithGetUrl:self.selectDate == 1? WKStudyMyQueryClockRecordByDate : WKStudyMyClockRecord withPostParams:dic.mutableCopy withBlock:^(NSDictionary *result, NSError *error) {
        hud.hidden = YES; 
        if ([result[@"code"]integerValue] == 200) {
            if (weakself.page == 1) {
                [self.sourceArray removeAllObjects];
            }
            
            for (NSDictionary *dic in result[@"data"]) {
                WKHotmenModel *model = [WKHotmenModel mj_objectWithKeyValues:dic];
                [self.sourceArray addObject:model];
            }
            if ([result[@"data"] count] < 10) {
                //不能加载更多数据
                [self checkFooterState];
                [MBProgressHUD showSuccess:@"已加载全部数据" toView:self.view];
            }else{
                [self.tableView.mj_footer endRefreshing];
            }
        }else{
//            [MBProgressHUD showSuccess:result[@"msg"] toView:self.view];
        }
        [weakself.tableView reloadData];
        
        [self.tableView.mj_header endRefreshing];
    }];
}
// 右边Item
- (void)setupRightItem{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setTitle:@"筛选" forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:16];
    button.frame = CGRectMake(0, 0, 40, 30);
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:button] ;

    [button addTarget:self action:@selector(buttonItemClick) forControlEvents:UIControlEventTouchUpInside];
}
- (void)buttonItemClick{
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = @"正在加载...";
    [hud show:YES];
    
    [WYHXNetWorkService netWorkSerViceRequestWithGetUrl:WKStudyMyQueryUserClockMonth withPostParams:@{@"token":[UserModel getUserModel].token}.mutableCopy withBlock:^(NSDictionary *result, NSError *error) {
        hud.hidden = YES;
        NSMutableArray *dataArray = [[NSMutableArray alloc]init];
        if ([result[@"code"]integerValue] == 200) {
            NSArray *data = result[@"data"];
            if (data.count>0) {
                for (NSDictionary *dic in result[@"data"]) {
                    [dataArray addObject:dic[@"date"]];
                }
                THScrollChooseView *scrollChooseView = [[THScrollChooseView alloc] initWithQuestionArray:dataArray withDefaultDesc:result[@"data"][0][@"date"] with:@"选择月份"];
                [scrollChooseView showView];
                scrollChooseView.confirmBlock = ^(NSInteger selectedQuestion) {
                    self.selectDate = 1;
                    self.dateString = dataArray[selectedQuestion];
                    //                NSLog(@"selectedQuestion:%ld",selectedQuestion);
                    [self setupLeftRefresh];
                };
            }

        }else{
            [MBProgressHUD showSuccess:result[@"msg"] toView:self.view];
        }
    }];
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.sourceArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
   
    VKRecordNiuWaCell *cell = [VKRecordNiuWaCell cellWithTableView:tableView];
    cell.followButton.layer.cornerRadius = 12;
    cell.followButton.layer.masksToBounds = YES;
    cell.followButton.layer.borderWidth = 1;
    cell.followButton.layer.borderColor = rgb(254,75,42).CGColor;
    cell.followButton.titleLabel.font = LBFont(12*kScaleFit);
    [cell.followButton setTitle:@"删除" forState:UIControlStateNormal];
    [cell.followButton setTitleColor:rgb(254,75,42) forState:UIControlStateNormal];
    cell.selectionStyle = UITableViewCellSeparatorStyleNone;
    cell.followButton.tag = indexPath.section + 8818;
    [cell.followButton addTarget:self action:@selector(deleteBtn:) forControlEvents:UIControlEventTouchUpInside];
    cell.model = self.sourceArray[indexPath.section];
    cell.zanButton.tag = indexPath.section;
    [cell.zanButton addTarget:self action:@selector(clickZanBtn:) forControlEvents:UIControlEventTouchUpInside];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 435;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    WKHotmenModel *model = self.sourceArray[indexPath.section];

    if (model.clockInfoVOList==0) {
        return;
    }
    if ([model.fileType isEqualToString:@"2"]) {
        WKDakaImageTextVC *imagetextVC = [WKDakaImageTextVC new];
        imagetextVC.model = model;
        [self.navigationController pushViewController:imagetextVC animated:YES];
    }else{//视频
        VKRecordDetailVC *detailVC = [VKRecordDetailVC new];
        detailVC.model = model;
        [self.navigationController pushViewController:detailVC animated:YES];
    }
    
}

// 赞
- (void)clickZanBtn:(UIButton *)sender{
    
    WKHotmenModel *model = self.sourceArray[sender.tag];
    
    if ([model.isPrase integerValue] == 1) { // 取消
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.labelText = @"正在加载...";
        [hud show:YES];
        NSMutableDictionary *dic = @{@"token":[UserModel getUserModel].token,@"clockId":model.clockId}.mutableCopy;        
        [WYHXNetWorkService netWorkSerViceRequestWithPostUrl:WKStudyMyCancelPraiseClock withPostParams:dic.mutableCopy withBlock:^(NSDictionary *result, NSError *error) {
            hud.hidden = YES;
            if ([result[@"code"]integerValue] == 200) {
                [MBProgressHUD showSuccess:@"取消成功" toView:self.view];
                model.isPrase = @"0";
                model.praiseNum = [NSString stringWithFormat:@"%d",[model.praiseNum intValue] - 1];
                [self.sourceArray replaceObjectAtIndex:sender.tag withObject:model];

            }else{
                [MBProgressHUD showSuccess:result[@"msg"] toView:self.view];
            }
            NSIndexSet *indexSet = [[NSIndexSet alloc]initWithIndex:sender.tag];
            [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationNone];
        }];
    }else{
     
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.labelText = @"正在加载...";
        [hud show:YES];
        NSMutableDictionary *dic = @{@"token":[UserModel getUserModel].token,@"clockId":model.clockId}.mutableCopy;
        
        [WYHXNetWorkService netWorkSerViceRequestWithPostUrl:WKStudyMyPraiseClock withPostParams:dic.mutableCopy withBlock:^(NSDictionary *result, NSError *error) {
            hud.hidden = YES;
            if ([result[@"code"]integerValue] == 200) {
                [MBProgressHUD showSuccess:@"点赞成功" toView:self.view];
                model.isPrase = @"1";
                model.praiseNum = [NSString stringWithFormat:@"%d",[model.praiseNum intValue] + 1];

                [self.sourceArray replaceObjectAtIndex:sender.tag withObject:model];

            }else{
                [MBProgressHUD showSuccess:result[@"msg"] toView:self.view];
            }
            
            NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:sender.tag];
            [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationNone];
        }];
    }

}

// 删除
- (void)deleteBtn:(UIButton *)sender{
    NSLog(@"%ld",sender.tag);
    
    WKHotmenModel *model = self.sourceArray[sender.tag - 8818];
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = @"正在加载...";
    [hud show:YES];
    NSMutableDictionary *dic = @{@"token":[UserModel getUserModel].token,@"clockId":model.clockId}.mutableCopy;
    VKWeakSelf(self)
    
    [WYHXNetWorkService netWorkSerViceRequestWithGetUrl:WKStudyMyDeleteClock withPostParams:dic.mutableCopy withBlock:^(NSDictionary *result, NSError *error) {
        hud.hidden = YES;
        if ([result[@"code"]integerValue] == 200) {
            [MBProgressHUD showSuccess:result[@"msg"] toView:self.view];
            [self setupLoadData];
        }else{
            [MBProgressHUD showSuccess:result[@"msg"] toView:self.view];
        }
        [weakself.tableView reloadData];
        
    }];
}

//- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
//    return 10;
//}
//- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
//    UIView *sectionHeader = [UIView new];
//    sectionHeader.backgroundColor =rgb(242,242,242);
//    return sectionHeader;
//}
@end
